package com.prs.crm.action.sale;

import java.util.Collection;
import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.struts.BaseAction;
import org.courser.ui.PaginationSupport;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;

import com.prs.crm.annotation.Clew;
import com.prs.crm.domain.fs.BankAccount;
import com.prs.crm.domain.fs.PayWay;
import com.prs.crm.domain.sale.Returns;
import com.prs.crm.domain.sale.ReturnsDetail;
import com.prs.crm.domain.sale.SalesContract;
import com.prs.crm.domain.sale.SalesContractDetail;
import com.prs.crm.domain.sale.SalesReceives;
import com.prs.crm.domain.sale.SalesReceivesRegist;
import com.prs.crm.domain.sale.SalesReceivesRegistBillReality;
import com.prs.crm.domain.sale.SalesShipping;
import com.prs.crm.domain.sale.SalesShippingDetail;
import com.prs.crm.domain.sys.Code;
import com.prs.crm.domain.sys.CodeInvoice;
import com.prs.crm.service.fs.BankAccountService;
import com.prs.crm.service.fs.PayWayService;
import com.prs.crm.service.sale.ReturnsService;
import com.prs.crm.service.sale.SaleInvoicesService;
import com.prs.crm.service.sale.SalesContractService;
import com.prs.crm.service.sale.SalesReceivesRegistBillRealityService;
import com.prs.crm.service.sale.SalesReceivesRegistService;
import com.prs.crm.service.sale.SalesReceivesService;
import com.prs.crm.service.sale.SalesShippingService;
import com.prs.crm.service.sys.CodeInvoiceService;
import com.prs.crm.service.sys.CodeService;

public class SalesReceivesAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private String Encode;

	private String recState;

	private String allmonys;

	private CodeInvoice codeInvoice;

	private CodeInvoiceService codeInvoiceService;

	private Code code;

	private CodeService codeService;

	private Collection<CodeInvoice> codelist;
	private SalesShipping salesShipping;

	private SalesReceivesRegist salesReceivesRegist;

	private SalesReceivesRegistBillReality salesReceivesRegistBillReality;

	private SalesReceives salesReceives;

	private SalesContract salesContract;
	private int type;

	private SalesReceivesService salesReceivesService;

	private SalesContractService salesContractService;

	private SalesReceivesRegistService salesReceivesRegistService;

	private SaleInvoicesService saleInvoicesService;
	private SalesShippingService salesShippingService;
	private String money;
	private ReturnsService returnsService;

	@Autowired
	private SalesReceivesRegistBillRealityService salesReceivesRegistBillRealityService;

	private BankAccountService bankAccountService;

	private PayWayService payWayService;

	private PaginationSupport pagination;

	private List<PayWay> typeWayList;

	private Collection<BankAccount> bankAccounts;

	private double states;

	@Action("editSalesReceives")
	public String editSalesReceives() {
		this.codelist = this.getCodeInvoiceService().getInvoiceCodeType(
				"销售收款单编号");
		return SUCCESS;
	}

	@Clew(results = { "success", "none" })
	@Action(value = "saveSalesReceives", results = {
			@Result(name = "success", type = "redirect", location = "listSalesReceives"),
			@Result(name = "error", type = "chain", location = "editSalesReceives"),
			@Result(name = "none", type = "redirect", location = "listSalesReceives") })
	public String saveSalesReceives() {

		if ("n".equals(Encode)) {
			int EncodeRplice = this.getCodeService().getBackRpliceAll("手动编码",
					"销售发货", salesReceives.getButonListCode());
			if (EncodeRplice != 0) {
				this.addActionError("编码重复!请重新输入");
				return ERROR;
			}
		}

		if (salesReceives.getSalesContract() == null) {
			this.addActionError("请添加关联发货单");
			return ERROR;
		}
		if (salesReceives.getButonListCode() == null
				|| salesReceives.getButonListCode().equals("")) {
			this.addActionError("请添加底单编号");
			return ERROR;
		}
		if (salesReceives.getReceiviceName() == null
				|| salesReceives.getReceiviceName().equals("")) {
			this.addActionError("请添加收款单主题");
			return ERROR;
		}
		if (salesReceives.getPlanDate() == null) {
			this.addActionError("请添加计划回款日期");
			return ERROR;
		}
		if (salesReceives.getPerson() == null) {
			this.addActionError("请添加销售人");
			return ERROR;
		}
		this.getSalesReceivesService().save(salesReceives);
		// if (Double.valueOf(money) - salesReceives.getAmount() == 0) {
		// salesShipping.setReceivesState(2);
		// } else {
		// salesShipping.setReceivesState(1);
		// }
		// salesShipping.setReceiveNumber(salesReceives.getAmount());

		/**
		 * 编码产生
		 */
		if ("n".equals(Encode)) {
			Code codes = new Code();
			codes.setCodeValue(salesReceives.getButonListCode());
			codes.setCodeMolde("销售发货");
			codes.setEntityName(this.getClass().getName());
			codes.setCodeType("手动编码");
			this.getCodeService().save(codes);
			salesReceives.setCode(codes);
			this.getSalesReceivesService().save(salesReceives);
		} else {
			CodeInvoice Vob = this.getCodeInvoiceService().getVobject(
					codeInvoice.getId());
			Code codes = new Code();
			codes.setCodeValue(salesReceives.getButonListCode());
			codes.setCodeMolde("销售发货");
			codes.setEntityName(this.getClass().getName());
			Vob.setNumBackUp(Increase(Vob.getNumBackUp()));
			this.getCodeInvoiceService().saveOrUpdate(Vob);
			codes.setCodeType(Vob.getCodePlan());
			this.getCodeService().save(codes);
			salesReceives.setCode(codes);
			this.getSalesReceivesService().save(salesReceives);
		}

		SalesContract salesContractObject = this.getSalesContractService()
				.getSalesContract(salesReceives.getSalesContract().getId());
		// System.out.println("得出对象=" + salesContractObject);
		// if ("1".equals(recState)) {
		// if (Double.parseDouble(allmonys) - salesReceives.getAmount() == 0.0)
		// {
		// salesContractObject.setReceiptState(3);
		// } else {
		// salesContractObject.setReceiptState(2);
		// salesContractObject.setContactMonly(Double
		// .parseDouble(allmonys)
		// - salesReceives.getAmount());
		// }
		// } else if ("2".equals(recState)) {
		// if (salesContractObject.getContactMonly() == 0.0) {
		// salesContractObject.setReceiptState(3);
		// } else if ((salesContractObject.getContactMonly() - salesReceives
		// .getAmount()) == 0.000) {
		// salesContractObject.setReceiptState(1);
		// salesContractObject.setContactMonly(salesContractObject
		// .getContactMonly()
		// - salesReceives.getAmount());
		// } else {
		// salesContractObject.setContactMonly(salesContractObject
		// .getContactMonly()
		// - salesReceives.getAmount());
		// }
		// }
		salesContractObject.setReceiveMoney(salesContractObject
				.getReceiveMoney()
				+ salesReceives.getAmount());
		if (Double.parseDouble(allmonys) - salesReceives.getAmount() == 0.0) {
			salesContractObject.setReceiptState(1);
		}
		this.getSalesContractService().saveOrUpdate(salesContractObject);
		this.setPrompt("操作成功");
		return SUCCESS;
	}

	@Clew(results = { "success", "none" })
	@Action(value = "saveSalesReceivesRegist", results = {
			@Result(name = "success", type = "redirect", location = "listSalesReceivesRegist"),
			@Result(name = "error", type = "chain", location = "salesReceivesRegist"),
			@Result(name = "none", type = "redirect", location = "listSalesReceivesRegist") })
	public String saveSalesReceivesRegist() {

		if ("n".equals(Encode)) {
			int EncodeRplice = this.getCodeService().getBackRpliceAll("手动编码",
					"销售底单", salesReceivesRegist.getBillCode());
			if (EncodeRplice != 0) {
				this.addActionError("编码重复!请重新输入");
				return ERROR;
			}
		}
		if (salesReceivesRegist.getBillDate() == null) {
			this.addActionError("请添加底单日期");
			return ERROR;
		}
		if (salesReceivesRegist.getBillAmount() == null) {
			this.addActionError("请添加底单金额");
			return ERROR;
		}
		if (salesReceivesRegist.getBillCode() == null
				|| salesReceivesRegist.getBillCode().equals("")) {
			this.addActionError("请添加底单编号");
			return ERROR;
		}
		SalesReceives SalesReceivesObject = this.getSalesReceivesService()
				.getSalesReceives(salesReceives.getId());
		SalesReceivesObject.setAmount(SalesReceivesObject.getAmount()
				- salesReceivesRegist.getBillAmount());

		/**
		 * 编码产生
		 */
		if ("n".equals(Encode)) {
			Code codes = new Code();
			codes.setCodeValue(salesReceivesRegist.getBillCode());
			codes.setCodeMolde("销售底单");
			codes.setEntityName(this.getClass().getName());
			codes.setCodeType("手动编码");
			this.getCodeService().save(codes);
			salesReceivesRegist.setCode(codes);
			this.getSalesReceivesRegistService().save(salesReceivesRegist);
		} else {
			CodeInvoice Vob = this.getCodeInvoiceService().getVobject(
					codeInvoice.getId());
			Code codes = new Code();
			codes.setCodeValue(salesReceivesRegist.getBillCode());
			codes.setCodeMolde("销售底单");
			codes.setEntityName(this.getClass().getName());
			Vob.setNumBackUp(Increase(Vob.getNumBackUp()));
			this.getCodeInvoiceService().saveOrUpdate(Vob);
			codes.setCodeType(Vob.getCodePlan());
			this.getCodeService().save(codes);
			salesReceivesRegist.setCode(codes);
			this.getSalesReceivesRegistService().save(salesReceivesRegist);
		}
		this.setPrompt("操作成功");
		return SUCCESS;
	}

	@Clew(results = { "success", "none" })
	@Action(value = "saveSalesReceivesRegistBill", results = {
			@Result(name = "success", type = "redirect", location = "listSalesReceivesRegistBillReality"),
			@Result(name = "error", type = "chain", location = "salesReceivesRegistBill"),
			@Result(name = "none", type = "redirect", location = "listSalesReceivesRegist") })
	public String saveSalesReceivesRegistBill() {
		if (salesReceivesRegistBillReality.getRealityDate() == null) {
			this.addActionError("请添加实际到账日期");
			return ERROR;
		}
		if (salesReceivesRegistBillReality.getPerson() == null) {
			this.addActionError("请添加入账人");
			return ERROR;
		}
		SalesContract contract = salesReceivesRegist.getSalesReceives()
				.getSalesContract();
		contract.setPayedMoney(contract.getPayedMoney()
				+ salesReceivesRegist.getBillAmount());
		SalesReceivesRegist salesReceivesRegistObject = this
				.getSalesReceivesRegistService().getSalesReceivesRegist(
						salesReceivesRegist.getId());
		salesReceivesRegistObject.setBillAmount(0.0);
		this.getSalesReceivesRegistBillRealityService().saveOrfund(
				salesReceivesRegistBillReality);
		this.getSalesContractService().save(contract);
		this.setPrompt("操作成功");
		return SUCCESS;
	}

	@Action("listSalesReceives")
	public String excute() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				SalesReceives.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		criteria.add(Restrictions.gt("amount", 0.0));
		this.setPagination(this.getSalesReceivesService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("listSalesReceivesRegist")
	public String excute1() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				SalesReceivesRegist.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		criteria.add(Restrictions.gt("billAmount", 0.0));
		this.setPagination(this.getSalesReceivesService().listByPage(criteria,
				pagination));
		return SUCCESS;
	}

	@Action("listSalesReceivesRegistBillReality")
	public String excute2() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				SalesReceivesRegistBillReality.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		criteria.add(Restrictions.eq("judgeValue", 0));
		this.setPagination(this.getSalesReceivesRegistBillRealityService()
				.listByPage(criteria, pagination));
		return SUCCESS;
	}

	/**
	 * 根据合同ID得到钱的总数
	 * 
	 * @return
	 */
	@Action(value = "salesReceivesAmount", results = { @Result(name = "success", type = "json", params = {
			"root", "states" }) })
	public String salesReceivesAmount() {

		// List<SalesContractDetail> details =
		// SalesContract contract = this.getSalesContractService().get(
		// salesContract.getId());
		try {
			for (SalesContractDetail detail : salesContract.getDetails()) {
				this.states = states + detail.getTotalPrice();

			}
			Double moneyDouble = 0.0;
			for (Returns returns : this.getReturnsService() 
					.getReturnsBysalesContract(salesContract)) {
				for (ReturnsDetail detail : returns.getDetails()) {
					moneyDouble = moneyDouble + detail.getTotalPrice();
				}
			}
			this.states = this.states - salesContract.getReceiveMoney()
					- moneyDouble+salesContract.getMoney();
		} catch (Exception e) {
			e.printStackTrace();// TODO: handle exception
		}

		return SUCCESS;
	}

	@Action("viewSalesReceives")
	public String viewSalesReceives() {
		salesReceives = this.getSalesReceivesService().get(
				salesReceives.getId());
		return SUCCESS;
	}

	@Action("salesReceivesRegist")
	public String salesReceivesRegist() {
		salesReceives = this.getSalesReceivesService().get(
				salesReceives.getId());

		this.typeWayList = this.getPayWayService().getAll();
		this.codelist = this.getCodeInvoiceService().getInvoiceCodeType(
				"销售收款底单");
		return SUCCESS;
	}

	@Action("salesReceivesRegistBill")
	public String salesReceivesRegistBill() {
		salesReceivesRegist = this.getSalesReceivesRegistService().get(
				salesReceivesRegist.getId());
		this.bankAccounts = this.getBankAccountService().getAllBankAccount();
		return SUCCESS;
	}

	@Action("viewSalesReceivesBill")
	public String viewSalesReceivesBill() {
		salesReceivesRegist = this.getSalesReceivesRegistService().get(
				salesReceivesRegist.getId());
		return SUCCESS;
	}

	public SalesReceives getSalesReceives() {
		return salesReceives;
	}

	public static String Increase(String backupNum) {
		String Inc = "";
		int lengths = backupNum.length();
		String lengthss = (Integer.parseInt(backupNum) + 1) + "";
		int increase = (lengthss.trim()).length();
		if (lengths != increase) {
			String In = "";
			for (int i = 0; i < lengths - increase; i++) {
				In = In + "0";
			}
			In = (In + lengthss).trim();
			Inc = In;
		} else {
			Inc = lengthss;
		}
		return Inc.trim();
	}

	public void setSalesReceives(SalesReceives salesReceives) {
		this.salesReceives = salesReceives;
	}

	public SalesReceivesService getSalesReceivesService() {
		return salesReceivesService;
	}

	public void setSalesReceivesService(
			SalesReceivesService salesReceivesService) {
		this.salesReceivesService = salesReceivesService;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public double getStates() {
		return states;
	}

	public void setStates(double states) {
		this.states = states;
	}

	public SalesContractService getSalesContractService() {
		return salesContractService;
	}

	public void setSalesContractService(
			SalesContractService salesContractService) {
		this.salesContractService = salesContractService;
	}

	public SalesContract getSalesContract() {
		return salesContract;
	}

	public void setSalesContract(SalesContract salesContract) {
		this.salesContract = salesContract;
	}

	public SalesReceivesRegist getSalesReceivesRegist() {
		return salesReceivesRegist;
	}

	public void setSalesReceivesRegist(SalesReceivesRegist salesReceivesRegist) {
		this.salesReceivesRegist = salesReceivesRegist;
	}

	public List<PayWay> getTypeWayList() {
		return typeWayList;
	}

	public void setTypeWayList(List<PayWay> typeWayList) {
		this.typeWayList = typeWayList;
	}

	public PayWayService getPayWayService() {
		return payWayService;
	}

	public void setPayWayService(PayWayService payWayService) {
		this.payWayService = payWayService;
	}

	public SalesReceivesRegistService getSalesReceivesRegistService() {
		return salesReceivesRegistService;
	}

	public void setSalesReceivesRegistService(
			SalesReceivesRegistService salesReceivesRegistService) {
		this.salesReceivesRegistService = salesReceivesRegistService;
	}

	public BankAccountService getBankAccountService() {
		return bankAccountService;
	}

	public void setBankAccountService(BankAccountService bankAccountService) {
		this.bankAccountService = bankAccountService;
	}

	public Collection<BankAccount> getBankAccounts() {
		return bankAccounts;
	}

	public void setBankAccounts(Collection<BankAccount> bankAccounts) {
		this.bankAccounts = bankAccounts;
	}

	public SalesReceivesRegistBillReality getSalesReceivesRegistBillReality() {
		return salesReceivesRegistBillReality;
	}

	public void setSalesReceivesRegistBillReality(
			SalesReceivesRegistBillReality salesReceivesRegistBillReality) {
		this.salesReceivesRegistBillReality = salesReceivesRegistBillReality;
	}

	public SalesReceivesRegistBillRealityService getSalesReceivesRegistBillRealityService() {
		return salesReceivesRegistBillRealityService;
	}

	public void setSalesReceivesRegistBillRealityService(
			SalesReceivesRegistBillRealityService salesReceivesRegistBillRealityService) {
		this.salesReceivesRegistBillRealityService = salesReceivesRegistBillRealityService;
	}

	public SaleInvoicesService getSaleInvoicesService() {
		return saleInvoicesService;
	}

	public void setSaleInvoicesService(SaleInvoicesService saleInvoicesService) {
		this.saleInvoicesService = saleInvoicesService;
	}

	public SalesShippingService getSalesShippingService() {
		return salesShippingService;
	}

	public void setSalesShippingService(
			SalesShippingService salesShippingService) {
		this.salesShippingService = salesShippingService;
	}

	public SalesShipping getSalesShipping() {
		return salesShipping;
	}

	public void setSalesShipping(SalesShipping salesShipping) {
		this.salesShipping = salesShipping;
	}

	public String getMoney() {
		return money;
	}

	public void setMoney(String money) {
		this.money = money;
	}

	public int getType() {
		return type;
	}

	public void setType(int type) {
		this.type = type;
	}

	public String getEncode() {
		return Encode;
	}

	public void setEncode(String encode) {
		Encode = encode;
	}

	public CodeInvoice getCodeInvoice() {
		return codeInvoice;
	}

	public void setCodeInvoice(CodeInvoice codeInvoice) {
		this.codeInvoice = codeInvoice;
	}

	public CodeInvoiceService getCodeInvoiceService() {
		return codeInvoiceService;
	}

	public void setCodeInvoiceService(CodeInvoiceService codeInvoiceService) {
		this.codeInvoiceService = codeInvoiceService;
	}

	public Code getCode() {
		return code;
	}

	public void setCode(Code code) {
		this.code = code;
	}

	public CodeService getCodeService() {
		return codeService;
	}

	public void setCodeService(CodeService codeService) {
		this.codeService = codeService;
	}

	public Collection<CodeInvoice> getCodelist() {
		return codelist;
	}

	public void setCodelist(Collection<CodeInvoice> codelist) {
		this.codelist = codelist;
	}

	public String getRecState() {
		return recState;
	}

	public void setRecState(String recState) {
		this.recState = recState;
	}

	public String getAllmonys() {
		return allmonys;
	}

	public void setAllmonys(String allmonys) {
		this.allmonys = allmonys;
	}

	public ReturnsService getReturnsService() {
		return returnsService;
	}

	public void setReturnsService(ReturnsService returnsService) {
		this.returnsService = returnsService;
	}

}
